package LeetCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}16:55
 */
public class LeetCode1 {

    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        System.out.println(Arrays.toString(new LeetCode1().twoSum2(arr, 9)));
    }

    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++){
            for (int j = i+1; j < nums.length; j++){
                if (nums[i]+nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{0};
    }

    public int[] twoSum2(int[] nums, int target){
        int i = 0;
        int j = nums.length - 1;
        if (nums.length <= 1){
            return new int[]{};
        }
        Arrays.sort(nums);
        Map<Integer,Integer> map = new HashMap<>();
        for (int k = 0; k < nums.length;k++){
            map.put(nums[k],k);
        }
        while ( i < j ){
            int sum = nums[i] + nums[j];
            if (sum > target){
                j--;
            }else if (sum < target){
                i++;
            }else {
                return new int[]{map.get(nums[i]),map.get(nums[j])};
            }
        }
        return new int[]{};
    }
}
